import logging
import os
import subprocess
import sys
from typing import Dict, Any

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('MCP-check')


def check_command_availability(command: str) -> bool:
    """检查命令是否可用

    Args:
        command: 要检查的命令

    Returns:
        命令是否可用
    """
    try:
        # 检查是否存在于环境PATH中
        result = subprocess.run(
            ["where" if sys.platform == "win32" else "which", command],
            capture_output=True,
            text=True,
            timeout=5
        )
        if result.returncode == 0:
            logger.info(f"命令 {command} 可用，路径: {result.stdout.strip()}")
            return True

        logger.warning(f"命令 {command} 不可用，尝试备用方法...")
        return False
    except Exception as e:
        logger.warning(f"检查命令时出错: {str(e)}")
        return False


def prepare_environment(tool_config: Dict[str, Any]) -> Dict[str, Any]:
    """准备工具执行环境

    Args:
        tool_config: 工具配置

    Returns:
        修改后的工具配置
    """
    config = tool_config.copy()

    # 检查和修正命令
    command = config.get("command")
    if command:
        # 检查命令是否可用
        is_available = check_command_availability(command)
        if not is_available:
            # 尝试常见的替代命令和扩展路径
            if command == "uvx":
                alternatives = ["uvicorn", "python -m uvicorn", sys.executable + " -m uvicorn"]
                for alt in alternatives:
                    if check_command_availability(alt.split()[0]):
                        logger.info(f"使用替代命令: {alt} 代替 {command}")
                        parts = alt.split()
                        config["command"] = parts[0]
                        if len(parts) > 1:
                            config["args"] = parts[1:] + config.get("args", [])
                        break

    # 确保有完整的PATH
    env = config.get("env", {})
    if not env:
        config["env"] = {}

    # 添加当前环境变量
    for key, value in os.environ.items():
        if key not in config["env"] and (key.upper() in ["PATH", "PYTHONPATH"] or
                                         key.startswith(("ANTHROPIC_", "OPENAI_", "MCP_", "PYTHON"))):
            config["env"][key] = value

    # 如果在虚拟环境中，确保包含虚拟环境的路径
    if sys.prefix != sys.base_prefix:
        venv_path = os.path.join(sys.prefix, "Scripts" if sys.platform == "win32" else "bin")
        path_var = "PATH"
        current_path = config["env"].get(path_var, os.environ.get(path_var, ""))
        if venv_path not in current_path:
            config["env"][path_var] = venv_path + os.pathsep + current_path

    return config
